<template>
  <div class="app-container">

    <!--新增按钮-->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input placeholder="关键词过滤" v-model="listQuery.query" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="handleFilter"/>

          <el-select v-model="listQuery.categoryId" placeholder="所属类别" clearable class="filter-item"
                     style="width: 150px" @change="handleFilter">
            <el-option v-for="{categoryId, categoryName} in categories" :key="categoryId" :label="categoryName"
                       :value="categoryId"/>
          </el-select>

          <el-select v-model="listQuery.orgCode" placeholder="所属商家" clearable class="filter-item"
                     style="width: 150px" @change="handleFilter" :disabled="isOrg">
            <el-option v-for="{orgCode, orgName} in orgs" :key="orgCode" :label="orgName"
                       :value="orgCode"/>
          </el-select>

          <el-select v-model="listQuery.validFlag" placeholder="有效标志" clearable class="filter-item" style="width: 150px"
                     @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value+'('+key+')'" :value="key"/>
          </el-select>

          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                     @click="handleCreate">新增
          </el-button>
          <el-checkbox v-model="showId" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+3">
            显示更多信息
          </el-checkbox>
        </div>
      </el-col>
    </el-row>

    <!--表格主体-->
    <el-row>
      <el-col :span="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :height="tableHeight"
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="100px">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column v-if="showId" label="产品ID" width="100px" align="center">
            <template slot-scope="scope">
              <span style="color:red;">{{ scope.row.productId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center">
            <template slot-scope="scope">
              {{ scope.row.productName }}
            </template>
          </el-table-column>
          <el-table-column label="所属类别" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.categoryId | categoryFilter(categories) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属商家" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.orgCode | orgFilter(orgs) }}</span>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="库存数量" width="110" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.hasSku | statusFilter">{{ scope.row.stockNum | stockNumFilter}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="商品价格" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品规格" align="center">
            <template slot-scope="scope">
              {{ scope.row.productSize}}
            </template>
          </el-table-column>

          <el-table-column v-if="showId" align="center" label="创建时间" show-overflow-tooltip>
            <template slot-scope="scope">
              <i class="el-icon-time"/>
              <span>{{ scope.row.createdTime | timeFilter}}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="showId" label="创建人" align="center">
            <template slot-scope="scope">
              {{ scope.row.createdUser}}
            </template>
          </el-table-column>

          <el-table-column class-name="status-col" label="有效标志" width="110" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.validFlag | statusFilter">{{ scope.row.validFlag | validFilter}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination v-show="total>0" :total="total"
                :page.sync="listQuery.pageNum"
                :limit.sync="listQuery.pageSize"
                layout="total, sizes, prev, pager, next"
                style="float:right;"
                @pagination="fetchData"/>

    <!--编辑弹窗-->
    <el-dialog :visible.sync="dialogFormVisible">

      <el-tabs @tab-click="handleTab" v-model="activeTab">
        <el-tab-pane label="基本信息" name="one">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px"
                   style="">

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商品名称" label-width="105px" prop="productName">
                  <el-input v-model="temp.productName" :disabled="dialogStatus === 'update'"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属类别" label-width="105px" prop="categoryId">
                  <el-select v-model="temp.categoryId" clearable class="filter-item" style="width: 150px"
                             @change="catChange">
                    <el-option v-for="{categoryId, categoryName} in categories" :key="categoryId" :label="categoryName"
                               :value="categoryId"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商品价格" label-width="105px" prop="price">
                  <el-input v-model.number="temp.price"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="库存数量" label-width="105px" prop="stockNum">
                  <el-input v-model.number="temp.stockNum"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商品规格" label-width="105px" prop="productSize">
                  <el-input v-model="temp.productSize"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品材料" label-width="105px" prop="productL2">
                  <el-input v-model="temp.productL2"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商品编号" label-width="105px" prop="productL1">
                  <el-input v-model="temp.productL1"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属商家" label-width="105px" prop="orgCode">
                  <el-select v-model="temp.orgCode" clearable class="filter-item" style="width: 150px" disabled>
                    <el-option v-for="{orgCode, orgName} in orgs" :key="orgCode" :label="orgName"
                               :value="orgCode"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="有效标志">
                  <el-switch
                    v-model="validSwitch"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="商品简述" label-width="105px" prop="productDesc">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    v-model="temp.productDesc">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>

          <div style="float:right;">
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="图片维护" name="second">
          <el-alert
            title="可以拖拽上传多张，最多上传3张"
            type="info">
          </el-alert>
          <div class="editor-container">
            <dropzone id="myVueDropzone" ref="mychild" :url="uploadUrl" @dropzone-removedFile="dropzoneR"
                      @dropzone-success="dropzoneS" @dropzone-successmultiple="successOk"/>
          </div>

          <el-alert ref="xxxx"
                    title="下方是添加成功的图片："
                    type="success"
                    close-text="嘿嘿嘿">
          </el-alert>

          <el-row>
            <el-col :span="4" v-for="(value, key, index) in imgArr" :key="key" :offset="index > 0 ? 1 : 0">
              <el-card :body-style="{ padding: '0px' }" v-if="value">
                <img :src="value" class="image">
                <div style="padding: 14px;">
                  <span>图片 {{key}} </span>
                  <el-button size="mini" round icon="el-icon-delete"> 删除</el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>

      </el-tabs>

    </el-dialog>

  </div>
</template>

<script>
  import {getInoPro, getListPro, getListProPage, updatePro, createPro, deletePro} from '@/api/manage/syPorduct'
  import SyCategoriesApi from '@/api/manage/syCategories';
  import SyOrgDictApi from '@/api/manage/syOrgDict';
  import waves from '@/directive/waves' // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import Dropzone from '@/components/Dropzone'
  import _ from 'lodash'

  export default {
    directives: {waves},
    components: {Pagination, Dropzone},
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      stockNumFilter(stockNum) {
        if (stockNum > 0) {
          return '有货 ' + stockNum
        } else {
          return '缺货 '
        }
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      },
      categoryFilter(id, categories) {
        let tempArr = categories.filter(item => item.categoryId === id)
        if (tempArr.length > 0) {
          return tempArr[0].categoryName
        } else {
          return ''
        }
      },
      orgFilter(id, orgs) {
        let tempArr = orgs.filter(item => item.orgCode === id)
        if (tempArr.length > 0) {
          return tempArr[0].orgName
        } else {
          return ''
        }
      },
    },
    data() {
      return {
        orgCode: '',
        isOrg: false,
        imgArr: {
          imageUrl1: '',
          imageUrl2: '',
          imageUrl3: '',
          imageUrl4: '',
          imageUrl5: ''
        }, //图片集合
        tableHeight: window.innerHeight - 220, //表格高度
        activeTab: 'one', //tab激活
        total: 0, // 分页总数
        orgs: [], //商家数据
        categories: [], //类别数据
        tableKey: 0, //表格key
        list: null, //表格对象
        listLoading: true, //表格加载框
        listQuery: { //表格查询对象
          pageNum: 1,
          pageSize: 5,
          query: '',
          validFlag: undefined,
          orgCode: '',
          categoryId: ''
        },
        showId: false, //是否展示ID
        temp: {}, //编辑框临时变量
        dialogFormVisible: false, //编辑框显示
        dialogStatus: '', //编辑框更新插入状态
        textMap: { //编辑框标题
          update: '编辑',
          create: '创建'
        },
        rules: { //表单校验规则
          productName: [{required: true, message: '类别名称不能为空', trigger: 'change'}],
          categoryId: [{required: true, message: '所属类别不能为空', trigger: 'change'}],
          price: [
            {required: true, message: '商品价格不能为空'},
            {type: 'number', message: '商品价格必须为数字值'}
          ],
          stockNum: [
            {required: true, message: '库存数量不能为空'},
            {type: 'number', message: '库存数量必须为数字值'}
          ]
        },
        statusOptions: { //有效无效下拉框
          '1': '有效',
          '0': '作废'
        },
        numberValidateForm: {
          sortNo: ''
        },
        productUrl: process.env.BASE_PRODUCT_IMG
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function () {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function (newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      },
      uploadUrl() {
        return process.env.BASE_API + 'syProductInfo/upload/' + this.temp.productId
      }
    },
    created() {
      if (this.$store.getters.roles.indexOf('common') !== -1) {
        this.orgCode = this.$store.getters.name;
        this.isOrg = true
        this.listQuery.orgCode = this.$store.getters.name;
      }
      this.fetchData()
    },
    mounted() {
    },
    methods: {
      fetchData() {
        let that = this;
        this.listLoading = true
        this.$http.all([SyCategoriesApi.getList({
          validFlag: '1',
          orgCode: this.orgCode
        }), SyOrgDictApi.getList({validFlag: '1'}), getListProPage(this.listQuery)])
          .then(this.$http.spread(function (acct, two, perms) {
            if (that.orgCode) {
              that.orgs = two.filter(item => item.orgCode === that.orgCode)
            } else {
              that.orgs = two
            }
            that.categories = acct
            that.orgs = two
            that.list = perms.rows
            that.total = perms.total
            that.listLoading = false
          }));
      },
      /**
       * 类别下拉框选择事件
       */
      catChange(value) {
        let that = this;
        let orgObj = _.find(that.categories, {categoryId: value});
        that.temp.orgCode = orgObj.orgCode;
      },
      /**
       * Tab操作
       */
      handleTab(tab, event) {
        let that = this;
        if (tab.index === '1' && !this.temp.productId) {
          this.$message({
            message: '必须先保存基本信息',
            type: 'warning',
            duration: 1000,
            onClose() {
              that.activeTab = 'one'
            }
          });
          return false;
        }
      },
      /**
       * 新增弹窗
       */
      handleCreate() {
        this.resetTemp()
        this.activeTab = 'one'
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
          this.$refs['mychild'].removeAllFiles();
        })
      },
      /**
       * 清空弹窗内容
       */
      resetTemp() {
        this.temp = {
          empName: '',
          empPw: '',
          validFlag: '1',
          roleType: '1',
          timestamp: new Date()
        }
      },
      /**
       * 确定新增
       */
      createData() {
        let that = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            createPro(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            })
          }
        })
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {
        this.activeTab = 'one'
        this.temp = Object.assign({}, row)
        this.updateImgArr(row);
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
          this.$refs['mychild'].removeAllFiles();
        })
      },
      /**
       * 确认编辑
       */
      updateData() {
        let that = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updatePro(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            })
          }
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        let that = this;
        deletePro({productId: row.productId}).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData();
            }
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.pageNum = 1
        this.fetchData()
      },
      dropzoneS(file) {
        //this.$message({ message: 'Upload success', type: 'success' })
      },
      dropzoneR(file) {
        this.$message({message: 'Delete success', type: 'success'})
      },
      successOk(file) {
        getInoPro(this.temp).then((row) => {
          this.updateImgArr(row);
          this.$message({message: '全部完成', type: 'success'})
        })
      },
      updateImgArr(row) {
        for (let p in row) {
          if (p.indexOf('imageUrl') !== -1 && row[p]) {
            if (row[p]) {
              this.imgArr[p] = this.productUrl + row[p];
            }
          }
        }
      }
    }
  }
</script>


<style>
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
</style>
